<script>
export default {
  name: 'SelfCascader',
  props: {
    value: {
      type: [Array, String, Number],
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    options: {
      type: [Array, Function],
      default: () => []
    },
    optionParams: {
      type: Object,
      default: () => ({})
    },
    props: {
      type: Object,
      default: () => ({
        label: 'label',
        value: 'value',
        children: 'children'
      })
    },
    formatOptions: {
      type: Function,
      default: options => options
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      optionsList: [],
      loading: false
    }
  },
  computed: {
    selectValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('update:value', val)
      }
    },
    optionsAndParamsAndKey() {
      return {
        options: this.options,
        optionParams: this.optionParams
      }
    }
  },
  watch: {
    optionsAndParamsAndKey: {
      handler() {
        this.resetValueAndOptions()
        this.getOptions()
      }
    }
  },
  mounted() {
    this.resetValueAndOptions()
    this.getOptions()
  },
  methods: {
    resetValueAndOptions() {
      this.selectValue = this.value || []
      this.optionsList = []
    },
    selfFormatOptions(options) {
      return options.map(item => {
        const { children } = item
        return {
          ...item,
          children: children && children.length > 0 ? this.selfFormatOptions(children) : undefined
        }
      })
    },
    async getOptions() {
      if (typeof this.optionsAndParamsAndKey.options === 'function') {
        this.loading = true
        try {
          const res = await this.optionsAndParamsAndKey.options(this.optionsAndParamsAndKey.optionParams)
          if (res.code === 200 && res.data) {
            this.optionsList = this.selfFormatOptions(res.data)
            this.formatOptions && (this.optionsList = this.formatOptions(this.optionsList))
          } else {
            this.optionsList = []
          }
        } finally {
          this.loading = false
        }
      } else {
        this.optionsList = this.optionsAndParamsAndKey.options
      }
    }
  }
}
</script>

<template>
  <el-cascader
    v-model="selectValue"
    v-loading="loading"
    :options="optionsList"
    :placeholder="placeholder"
    clearable
    filterable
    multiple
    collapse-tags
    :props="props"
    :show-all-levels="false"
    :disabled="disabled"
  />
</template>

<style scoped>

</style>
